package A;

public class ProducerCustomer {


    private volatile int tail = 0;
    private volatile int head = 0;
    private volatile int[] array = new int[100];
    private volatile int size = 0;

    public void put(int val) throws InterruptedException {
        synchronized (this) {
            while (size == array.length) {
                wait();
            }
            array[tail++] = val;
            if (tail == array.length) {
                tail = 0;
            }
            size++;
            notify();
        }
    }

    public int get() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                wait();
            }
            int res = array[head++];
            if (head == array.length) {
                head = 0;
            }
            size--;
            notify();
            return res;
        }
    }

    public static void main(String[] args) {
        ProducerCustomer p = new ProducerCustomer();
        Thread t = new Thread() {
            @Override
            public void run() {
                for (int i=0;i<100;i++){
                    try {
                        System.out.println("生产:"+i);
                        p.put(i);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i=0;i<10000;i++){
                    try {
                        System.out.println("消费："+p.get());
                        sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
        t1.start();
    }
}
